#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>


int connectsock(const char *host,const char *service,const char* transport)
{
    int sock;
    struct sockaddr_in saddr ={0};
    saddr.sin_family = AF_INET;
    struct servent *ent = getservbyname(service,transport);
    if(ent)
    {
        saddr.sin_port = ent->s_port;
    }
    else
    {
        if((saddr.sin_port = htons(atoi(service))) == 0)
        {
            printf("error!\n");
            exit(-1);
        }
        printf("#%s=%d\n",service,saddr.sin_port);
    }
    struct hostent *hent = gethostbyname(host);
    if(hent)
    {
        memcpy(&saddr.sin_addr,hent->h_addr,hent->h_length);
    }
    else
    {
        if((saddr.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE)
        {
            printf("error,can't get address from %s",host);
            exit(-1);
        }
        printf("####\n");
    }
    int type;
    struct protoent *pent = getprotobyname(transport);
    if(pent)
    {
        if(0 == strcmp(transport,"udp"))
            type = SOCK_DGRAM;
        else
            type = SOCK_STREAM;
        sock = socket(AF_INET,type,pent->p_proto);
        if(-1 == sock)
        {
            printf("error,socket() fail:%s",strerror(errno));
            exit(-1);
        }
        printf("##proto:%d\n",pent->p_proto);
    }
    else
    {
        printf("can't get proto from:%s",transport);
        exit(-1);
    }
    
    printf("%s:%d:%d\n", inet_ntoa(saddr.sin_addr), saddr.sin_port, pent->p_proto);
    
    if(connect(sock,(sockaddr*)&saddr,sizeof(saddr)) == -1)
    {
        printf("can't connect:%s",strerror(errno));
        exit(-1);
    }
    return sock;
}

int connectUDP(const char* host,const char* service)
{
    return connectsock(host,service,"udp");
}

int connectTCP(const char* host,const char* service)
{
    return connectsock(host,service,"tcp");
}

/*

int main(int argc,char *argv[])
{
    int sock = connectUDP("192.168.1.30","3000");
    char buf[] = "hello";
    int s = write(sock, buf, strlen(buf));
    printf("size %d wrote\n",s);
}

*/
